// Local Includes
#include "stdafx.h"
#include "MyImage.h"



// Tiff Includes
#include "tiffio.h"

// SDL Includes
#include <SDL_opengl.h>

// System Includes
#include <stdio.h>
#include <iostream>

MyImage::MyImage()
: _ePxlType(GL_UNSIGNED_BYTE),
  _eTexType(GL_TEXTURE_2D),
  _eTexComp(GL_RGBA),
  _eTexOp(GL_REPLACE),
  _iTexChan(0),
  _iTexMode(0),
  _iWidth(0),
  _iHeight(0),
  _bTexBind(false),
  _cTexID(0),
  _pData(NULL),
  _bLoaded(false)
{
}


MyImage::~MyImage()
{
    if (_pData) 
        _TIFFfree(_pData);
}


bool 
MyImage::loadImage( const char* pChar )
{
	_bLoaded = false;
    TIFF* tif = TIFFOpen(pChar, "r");
    if (tif) {
        
        
        TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &_iWidth);
        TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &_iHeight);
       
        int nPixels = _iWidth * _iHeight;
        _pData = (unsigned int*) _TIFFmalloc(nPixels * sizeof (unsigned int));

        if ( _pData && TIFFReadRGBAImage(tif, _iWidth, _iHeight, _pData, 0)) 
        {
            std::cout << "Succeffuly Read Tif" << std::endl;
			_bLoaded = true;
	    }
        TIFFClose(tif);       
    }    

    return true;
}

bool 
MyImage::setTexOp( unsigned int op )
{
    _eTexOp = op;
    return true;
}

bool 
MyImage::setTexChan( unsigned int chan )
{
    _iTexChan = chan;
    return true;
}

bool 
MyImage::bindTexture()
{
    if ( !_bTexBind ) {
        glGenTextures(1,(GLuint *)&_cTexID);
        glBindTexture(_eTexType, _cTexID);
        glTexImage2D( _eTexType, 0, _eTexComp, 
                      _iWidth, _iHeight, 0, 
                      _eTexComp, _ePxlType, (void*)_pData );

        glTexParameteri(_eTexType,GL_TEXTURE_MIN_FILTER,GL_LINEAR);	// Linear Filtering
		glTexParameteri(_eTexType,GL_TEXTURE_MAG_FILTER,GL_LINEAR);	// Linear Filtering
        glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, _eTexOp );

        _bTexBind = true;
    } else {
        glBindTexture(_eTexType, _cTexID);
    }

    return true;
}

bool 
MyImage::enableTexture()
{
    //glActiveTexture( GL_TEXTURE0 + _iTexChan );
    glEnable( _eTexType ); 
    return true;
}

bool 
MyImage::disableTexture()
{
    //glActiveTexture( GL_TEXTURE0 + _iTexChan );
    glDisable( _eTexType );
    return true;
}